package threading;


/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-07-04
 * Time: 14:51
 */
//懒汉模式
class SingletonLazy {
        volatile private static SingletonLazy instance = null;//volatile保证new的过程，不会指令重排序

        public static SingletonLazy getInstance() {
            if (instance == null) {//减少加锁的次数，不为空不必再加锁
                synchronized (SingletonLazy.class) {//保证多线程下，不会创建多个对象
                    if (instance == null) {//判断两次，保证多线程只有一个对象
                        instance = new SingletonLazy();
                    }
                }
            }
            return instance;
        }

        private SingletonLazy() {};
}

public class ThreadDemo18 {
    public static void main(String[] args) {
        SingletonLazy s1 = SingletonLazy.getInstance();
        SingletonLazy s2 = SingletonLazy.getInstance();

        System.out.println(s1 == s2);
    }
}
